/*
 * @Auther:hantianbing
 * @Date:2022/12/9
 * @Description:UserService的实现类， 实现userService的方法
 */
package com.sd365.permission.centre.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.common.aop.MyPageInfo;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BusinessErrorCode;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.util.BeanUtil;
import com.sd365.common.util.StringUtil;
import com.sd365.permission.centre.dao.mapper.*;
import com.sd365.permission.centre.entity.*;
import com.sd365.permission.centre.pojo.dto.RoleDTO;
import com.sd365.permission.centre.pojo.dto.UserDTO;
import com.sd365.permission.centre.pojo.query.UserQuery;
import com.sd365.permission.centre.pojo.vo.*;
import com.sd365.permission.centre.service.UserService;

import com.sd365.permission.centre.service.util.Md5Utils;
import com.sd365.permission.centre.service.util.UserRoleResourceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName UserServiceImpl
 * @Description 实现UserService接口的方法， 主要的功能实现类
 * @Author hantianbing
 * @Date 2022/12/9 10:49
 **/
@Service
public class UserServiceImpl extends AbstractBaseDataServiceImpl implements UserService {
    /**
     * 用来操作用户表
     */
    @Autowired
    private UserMapper userMapper;

    /**
     * 用来操作角色表
     */
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 用来操作用户角色表
     */
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 用来操作部门表
     */
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 用来操作position表
     */
    @Autowired
    private PositionMapper positionMapper;

    /**
     * 用来生成id， 在common包
     */
    @Autowired
    private IdGenerator idGenerator;

    /**
     * 用来操作公司表
     */
    @Autowired
    private CompanyMapper companyMapper;

    /**
     * 用来操作组织表
     */
    @Autowired
    private OrganizationMapper organizationMapper;

    @Override
    public Boolean add(UserDTO userDTO) {
        //非空判断
        if(userDTO == null){
            throw new BusinessException("100", "userDTO不能是空");
        }
        //code不能一样
        if(userMapper.selectByCode(userDTO.getCode()) != null){
            throw new BusinessException("100", "code已经存在了");
        }

        //插入用户
        User userO = BeanUtil.copy(userDTO, User.class);
        User user = setUserProperties(userO);
        if (userMapper.insertSelective(user)<=0) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户插入失败"));
        }

        //插入用户角色
        List<UserRole> userRoles = getUserRoles(user.getId(), userDTO.getRoleList());
        for (UserRole userRole : userRoles) {
            if (userRoleMapper.insert(userRole)<=0) {
                throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户角色插入失败"));
            }
        }
        return true;
    }

    @Override
    public Boolean remove(Long id, Long version) {
        // 非空判断， id version不能为空
        if(id == null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID,new Exception("用户的id为空"));
        }
        if(version==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户的版本为空"));
        }
        //删除和用户相关的条目
        if(!deleteAllUserRoleByUserId(id)){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户角色删除失败"));
        }
        //删除操作
        if (userMapper.deleteByPrimaryKey(id)<=0) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户删除失败"));
        }
        return true;
    }


    @Override
    public Boolean modify(@Valid UserDTO userDTO) {
        //用户必须存在
        if(userMapper.selectByPrimaryKey(userDTO.getId())==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户不存在"));
        }

        //工号不能重复
        if(!userMapper.selectByPrimaryKey(userDTO.getId()).getCode().equals(userDTO.getCode()) && userMapper.selectByCode(userDTO.getCode())!=null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户的code信息已经存在"));
        }



        //对用户进行操作操作，准备插入
        User user = BeanUtil.copy(userDTO, User.class);
        super.baseDataStuff4Updated(user);

        //更新用户的角色
        UserDTO[] userDTOS = new UserDTO[1];
        userDTOS[0] = userDTO;
        this.modifyWithNewRole(userDTOS);

        //更新用户自己的信息
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("id", user.getId());
        if(userMapper.updateByExampleSelective(user, example)>0){
            return true;
        }else{
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户更新失败"));
        }
    }

    @Override
    public Boolean modifyWithNewRole(UserDTO[] userDTOS) {
        //清除原有的所有数据
        List<Long> userIds = UserRoleResourceUtils.getUserIdsFromUserDTOArray(userDTOS);
        if (!deleteAllUserRoleByUserIds(userIds)) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户角色删除失败"));
        }
        //构建所有的userRole条目
        List<UserRole> userRoles = new ArrayList<>();
        for (UserDTO userDTO : userDTOS) {
            //获取roleList
            List<RoleDTO> roleList = userDTO.getRoleList();
            if(roleList == null){
                throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("角色列表为空"));
            }
            for (RoleDTO roleDTO : roleList) {
                //获取角色用户
                UserRole userRole = getUserRole(roleDTO.getId(), userDTO.getId());
                userRoles.add(userRole);
            }
        }
        //插入所有的userRole
        for (UserRole userRole : userRoles) {
            if (userRoleMapper.insert(userRole)<=0) {
                throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户角色插入失败"));
            }
        }
        return true;
    }

    @Override
    public List<UserVO> commonQuery(UserQuery userQuery) {
        //设置分页
        PageHelper.startPage(userQuery.getPageNum(), userQuery.getPageSize());
        List<User> users = userMapper.commonQuery(userQuery);
        Page<User> page = (Page<User>) users;
        BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
        List<UserVO> userVOS = BeanUtil.copyList(users, UserVO.class);
        //填补信息
        for (UserVO userVO : userVOS) {
            //设置company
            Company company = companyMapper.selectById(userVO.getCompanyId());
            if(company !=null){
                userVO.setCompany(BeanUtil.copy(company, CompanyVO.class));
                userVO.setCompanyName(userVO.getCompany().getName());
            }
            //设置Department
            Department department = departmentMapper.selectById(userVO.getDepartmentId());
            if(department !=null){
                userVO.setDepartment(BeanUtil.copy(department, DepartmentVO.class));
            }
            //设置organization
            Organization organization = organizationMapper.selectByPrimaryKey(userVO.getOrgId());
            if(organization !=null){
                userVO.setOrganizationVO(BeanUtil.copy(organization, OrganizationVO.class));
            }
            //设置position
            Position position = positionMapper.selectPositionById(userVO.getPositionId());
            if(position !=null){
                userVO.setPosition(BeanUtil.copy(position, PositionVO.class));
            }
            //设置角色
            List<Role> roles = roleMapper.selectRolesByUserId(userVO.getId());
            if(roles!=null){
                userVO.setRoleList(BeanUtil.copyList(roles, RoleVO.class));
            }
        }
        return userVOS;
    }

    @Override
    public UserVO queryUserById(Long id) {
        //非空判断
        if(id ==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户的id为空"));
        }
        //查询用户
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户不存在"));
        }
        //封装VO
        UserVO userVO = BeanUtil.copy(user, UserVO.class);
        //添加角色信息
        List<Long> roleIds = userRoleMapper.selectByUserId(id).stream().map(UserRole::getRoleId).collect(Collectors.toList());
        if(roleIds!=null || roleIds.size()!=0){
            List<RoleVO> userRoles = new ArrayList<>();
            for (Long roleId : roleIds) {
                Role role = roleMapper.selectByPrimaryKey(roleId);
                if(role==null){
                    continue;
                }
                userRoles.add(BeanUtil.copy(role, RoleVO.class));
            }
            //设置角色列表
            userVO.setRoleList(userRoles);
        }
        return userVO;
    }



    @Override
    public List<Role> queryAllRole() {
        List<Role> roles = roleMapper.queryAllRole();
        return roles;
    }

    @Override
    public List<Department> queryAllDepartment() {
        List<Department> departments = departmentMapper.queryAllDepartment();
        return departments;
    }

    @Override
    public List<Position> queryAllPosition() {
        List<Position> positions = positionMapper.queryAllPosition();
        return positions;
    }

    @Override
    public Boolean batchUpdate(UserDTO[] userDTOS) {
        //userDTOS 判空
        if(userDTOS == null || userDTOS.length == 0){
            return false;
        }
        //循环处理
        for (UserDTO userDTO : userDTOS) {
            if(userMapper.selectById(userDTO.getId())==null){
                continue;
            }
            if(userMapper.updateStatus(BeanUtil.copy(userDTO, User.class))<=0){
                throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户状态更新失败"));
            }
        }
        return true;
    }

    @Override
    public Boolean batchDelete(UserDTO[] userDTOS) {
        //非空判断
        if(userDTOS==null || userDTOS.length==0){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户DTO为空"));
        }
        //先删除所有的用户角色
        List<Long> userIds = UserRoleResourceUtils.getUserIdsFromUserDTOArray(userDTOS);
        if (!deleteAllUserRoleByUserIds(userIds)) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户角色删除失败"));
        }
        //删除所所有的用户
        Example example = new Example(User.class);
        example.createCriteria().andIn("id", userIds);
        if (userMapper.deleteByExample(example)<=0) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户删除失败"));
        }
        return true;
    }

    /***
     * @Description 获取角色list
     * @param userId  用户id
     * @param roleList  用户的角色的列表
     * @return java.util.List<com.sd365.permission.centre.entity.UserRole>
     * @Date 2022/12/26 9:53
     * @Author hantianbing
     **/
    private List<UserRole> getUserRoles(Long userId, List<RoleDTO> roleList ){
        List<UserRole> userRoles = new ArrayList<>();
        for (RoleDTO roleDTO : roleList) {
            UserRole userRole = getUserRole(roleDTO.getId(), userId);
            userRoles.add(userRole);
        }
        return userRoles;
    }

    /***
     * @Description 构建userRole， 通过用户id，角色id
     * @param roleId   角色id
     * @param userId   用户id
     * @return com.sd365.permission.centre.entity.UserRole
     * @Date 2022/12/26 9:55
     * @Author hantianbing
     **/
    private UserRole getUserRole(Long roleId, Long userId){
        //非空判断
        if(roleId ==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户的角色id为空"));
        }
        if(userId ==null){
            throw new BusinessException(BusinessErrorCode.SYSTEM_SERVICE_ARGUMENT_NOT_VALID, new Exception("用户id为空"));
        }
        //新建用户
        UserRole userRole = new UserRole();
        //设置id
        userRole.setId(idGenerator.snowflakeId());
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        //设置其他信息
        userRole.setVersion(INITIALIZE_VERSION_VALUE);
        super.baseDataStuffCommonPros(userRole);
        super.baseDataStuff4Add(userRole);
        return userRole;
    }


    /***
     * @Description 删除全部的userRole通过userIds
     * @param userIds  用户ids
     * @return java.lang.Boolean
     * @Date 2022/12/26 9:57
     * @Author hantianbing
     **/
    private Boolean deleteAllUserRoleByUserIds(List<Long> userIds){
        Example example = new Example(UserRole.class);
        example.createCriteria().andIn("userId", userIds);
        //删除数据
        if(userRoleMapper.deleteByExample(example)<0){
            return false;
        }
        return true;
    }

    /***
     * @Description 设置用户属性
     * @param user   要设置的用户
     * @return com.sd365.permission.centre.entity.User
     * @Date 2022/12/26 9:57
     * @Author hantianbing
     **/
    private User setUserProperties(User user){
        //设置属性
        user.setVersion(INITIALIZE_VERSION_VALUE);
        user.setStatus(INITIALIZE_STATUS_VALUE);
        user.setId(idGenerator.snowflakeId());
        super.baseDataStuff4Add(user);
        super.baseDataStuffCommonPros(user);

        //密码加密
        String s = Md5Utils.digestHex(user.getPassword());
        user.setPassword(s);

        return user;
    }

    /***
     * @Description 删除所有的userRole， 通过user的id
     * @param id   用户id
     * @return java.lang.Boolean
     * @Date 2022/12/26 9:57
     * @Author hantianbing
     **/
    private Boolean deleteAllUserRoleByUserId(Long id){
        //删除userRole，成功返回true， 失败false
        if(userRoleMapper.deleteAllByUserID(id)<0){
            return false;
        }else{
            return true;
        }
    }

    @Override
    public Boolean firstStartMd5() {
        return null;
    }

    @Override
    public Boolean updatePassword(UserDTO userDTO) {
        return null;
    }

    @Override
    public User getUser(String code) {
        return null;
    }
}
